﻿using System;
using System.Web;
using System.Web.Mvc;

namespace CodeCamp.Infrastructure
{
    public class RequireSSLForAzureWebService : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpRequestBase req = filterContext.HttpContext.Request;
            HttpResponseBase resp = filterContext.HttpContext.Response;

            if (!req.IsSecureConnection && !req.IsLocal)
            {
                Nullable<FederatedAuthConfig.PlatformType> configuredPlatform;
                FederatedAuthConfig.GetWIFConfigName(new DefaultValueProvider(), out configuredPlatform);
                if (!configuredPlatform.HasValue
                    || (configuredPlatform.Value == FederatedAuthConfig.PlatformType.azhsProd)
                    || (configuredPlatform.Value == FederatedAuthConfig.PlatformType.azhsStage))
                {
                    var builder = new UriBuilder(req.Url)
                    {
                        Scheme = Uri.UriSchemeHttps,
                        Port = 443
                    };
                    resp.Redirect(builder.Uri.ToString());
                }
            }

            base.OnActionExecuted(filterContext);
        }
    }
}